package com.fine.hair.manage.config;


import cn.hutool.core.util.ObjectUtil;
import com.fine.hair.comm.exception.BusinessException;
import com.fine.hair.comm.utils.ApiResponse;
import com.fine.hair.comm.vo.rbac.JwtResponse;
import com.fine.hair.comm.vo.rbac.LoginSuccVo;
import com.fine.hair.comm.model.Branch;
import com.fine.hair.comm.model.SecUser;
import com.fine.hair.manage.mapper.BranchMapper;
import com.fine.hair.manage.mapper.SecUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

/**
 * @author junelee
 * @date 2020/7/6 16:19
 */
@Service
public class LoginService {

    @Resource
    private SecUserMapper secUserMapper;

    @Autowired
    private BranchMapper branchMapper;

    public ApiResponse<LoginSuccVo> buildLoginSuccInfo(String jwt, String usernameOrPhone) {
        // 初始化vo
        LoginSuccVo vo = new LoginSuccVo();
        // 查询用户名
        SecUser secUser = secUserMapper.findByUsernameOrNameOrPhone(usernameOrPhone, usernameOrPhone);
        JwtResponse jwtResponse = new JwtResponse(jwt);
        // build
        vo.setJwtResponse(jwtResponse);
        vo.setUsername(secUser.getUsername());
        vo.setUserId(secUser.getId().toString());
        vo.setBranchId(secUser.getBranchId());
        vo.setPhone(secUser.getPhone());
        if (ObjectUtil.isNotNull(secUser.getBranchId())) {
            Branch branch = branchMapper.selectById(secUser.getBranchId());
            if (ObjectUtil.isNull(branch)) {
                throw new BusinessException("当前门店不存在");
            }
            vo.setBranchName(branch.getTitle());
        }
        return ApiResponse.ofSuccess(vo);
    }
}
